package custom.base.ui.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import custom.base.R;
import custom.base.http.AppApi;
import custom.base.http.listener.AliveCallback;
import custom.base.http.retrofit.IRequest;
import custom.base.log.MLog;
import custom.base.ui.activity.AppManager;
import retrofit2.Call;
import retrofit2.Callback;

/**
 * Created by luozi on 2016/3/7.
 */
public abstract class BaseFragment extends Fragment implements FragmentInterface,
        View.OnClickListener, AliveCallback {
    /**
     * 任务队列列表
     */
    List<Call> requestList;
    /**
     * 网络请求服务
     */
    public AppApi appApi;

    @Override
    public final void onCreate(Bundle savedInstanceState) {
        befordCreateView(savedInstanceState);
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public final View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view;

        int layoutID = getLayoutID();
        if (layoutID != 0) {
            view = inflater.inflate(getLayoutID(), null);
        } else {
            view = getLayoutView();
        }
        ButterKnife.bind(this, view);

        initNetWork();
        init(view, savedInstanceState);

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onFragmentClick(v);
            }
        });
        return view;
    }

    /**
     * 基础初始化
     */
    private void initNetWork() {
        requestList = new ArrayList<>();
        appApi = IRequest.getInstance(getContext()).getAppApi();
    }

    /**
     * 添加请求访问，调用此方法添加的话，会在activity结束的时候取消接口的请求，如果已经请求成功的话则忽略
     */
    protected Call addRequestCall(Call call, Callback callback) {
        if (getActivity() == null)
            return null;
        if (call != null && requestList != null)
            requestList.add(call);
        if (call != null)
            call.enqueue(callback);
        return call;
    }

    /**
     * 取消所有任务
     */
    protected void cancelAllRequestCall() {
        //循环取消未完成的任务
        if (requestList != null)
            for (int i = 0; i < requestList.size(); i++) {
                Call call = requestList.get(i);
                MLog.d(getMTag(), "移除请求任务: " + call);
                call.cancel();
            }

        //清除所有缓存列表
        requestList.clear();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }


    /**
     * 自定义的界面恢复回调
     */
    public void onFragmentResume() {

    }

    /**
     * 方法回调顺序
     * 1.initView
     * 2.initClss
     * 3.initData
     * 4.initListener
     *
     * @param savedInstanceState
     */
    private void init(@NonNull View view, @NonNull Bundle savedInstanceState) {
        initView(view, savedInstanceState);
        initObject(savedInstanceState);
        initData(savedInstanceState);
        initListener();

    }

    /**
     * 得到本类名
     */
    protected String getMTag() {
        return getResources().getString(R.string.app_name) + "#" + getClass().getSimpleName();
    }

    @Override
    public void onDestroy() {
        cancelTask();
        super.onDestroy();
        AppManager.getInstance().removeActivity(getActivity());
    }

    @Override
    public void onDestroyView() {
        cancelTask();
        super.onDestroyView();
    }

    private void cancelTask() {
        //循环取消未完成的任务
        if (requestList != null) {
            for (int i = 0; i < requestList.size(); i++) {
                Call call = requestList.get(i);
                MLog.d(getMTag(), "移除请求任务: " + call);
                call.cancel();
            }
            //清除所有缓存列表
            requestList.clear();
            requestList = null;
        }
    }

    @Override
    public final void onClick(View v) {
        onClick(v, v.getId());
    }

    /**
     * 单击回调
     *
     * @param v       点击的view
     * @param clickID 点击的控件id
     */
    public void onClick(View v, int clickID) {

    }

    /**
     * 默认不适用此方法，在子类里可以重构他
     */
    @Override
    public View getLayoutView() {
        return null;
    }

    //=====================setContentView 前回调

    @Override
    public void befordCreateView(@NonNull Bundle savedInstanceState) {

    }

    //=================创建后回调
    @Override
    public void initView(@NonNull View view, @NonNull Bundle savedInstanceState) {
    }

    @Override
    public void initObject(@NonNull Bundle savedInstanceState) {

    }

    @Override
    public void initData(@NonNull Bundle savedInstanceState) {

    }

    @Override
    public void initListener() {

    }

    /**
     * 当本界面被点击时
     */
    public void onFragmentClick(View v) {

    }


    //============================================网络回调

    protected AliveCallback getAliveCallback() {
        return this;
    }

    /**
     * 快捷开启activity
     */
    public void startActivity(Class<?> cls) {
        startActivity(new Intent(getActivity(), cls));
    }

    public boolean activityIsAlive() {
        Activity currentActivity = getActivity();
        if (currentActivity == null) return false;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            return !(currentActivity.isDestroyed() || currentActivity.isFinishing());
        } else {
            return !currentActivity.isFinishing();
        }
    }

    @Override
    public boolean isAlive() {
        return activityIsAlive();
    }

    @Override
    public Activity currentContext() {
        return getActivity();
    }
}
